package rentel.logbook.user;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

public class LogbookUserFormValidator implements Validator {

	private enum ErrorMessages {
		EMPTY_NAME("Name is empty!"),
		EMPTY_SURNAME("Surname is empty!"),
		EMPTY_USER_NAME("Username is empty!"),
		EMPTY_PASSWORD("Password is empty!"),
		PASSWORDS_NO_MATCH("Paswords no match!");
		
		private final String value;
		
		private ErrorMessages(String value) {
			this.value = value;
		}
		
		public String getValue() {
			return value;
		}
	}
	
	public boolean supports (Class<?> aClass) {
		return LogbookUser.class.equals(aClass);
	}

	public void validate (Object target, Errors errors) {
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "noCode", ErrorMessages.EMPTY_NAME.getValue());
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname", "noCode", ErrorMessages.EMPTY_SURNAME.getValue());
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userName", "noCode", ErrorMessages.EMPTY_USER_NAME.getValue());
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userPassword", "noCode", ErrorMessages.EMPTY_PASSWORD.getValue());
		
		LogbookUser user = (LogbookUser) target;
		
		String password = user.getUserPassword();
		String password1 = user.getUserPassword1();
		if (!password.equals(password1)) {
			errors.rejectValue("userPassword", "noCode", ErrorMessages.PASSWORDS_NO_MATCH.getValue());
		}
	}

}
